<template>
  <div class="page">
    <!-- 搜索区域 开始 -->
    <div class="el_card_box">
      <el-form :inline="true" size="small" :model="formInline" class="search_form">
        <el-form-item label="预约时间：">
          <el-date-picker v-model="formInline.orderTime" type="daterange" unlink-panels :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名时间：">
          <el-date-picker v-model="formInline.applyTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收款时间：">
          <el-date-picker v-model="formInline.orderTime2" type="daterange" unlink-panels :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="城市：">
          <!-- <el-select v-model="formInline.city" filterable clearable>
            <el-option v-for="(item,index) in cityList" :key="index" :label="item.name" :value="item.code"></el-option>
          </el-select> -->
          <city-select v-model="formInline.cities" @change="getHospital"></city-select>
        </el-form-item>
        <el-form-item label="预约医院：">
          <el-select v-model="formInline.hospital" filterable clearable>
            <el-option v-for="(item,index) in hospitalList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款类型：">
          <el-select v-model="formInline.dealType" filterable clearable>
            <el-option v-for="(item,index) in DEALLISTTYPELIST" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人：">
          <!-- <el-select v-model="formInline.principal" filterable clearable>
            <el-option v-for="(item,index) in userList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
          <user-select v-model="formInline.principals"></user-select>
        </el-form-item>
        <el-form-item label="成交项目：">
          <!-- <el-select v-model="formInline.project" filterable clearable>
            <el-option v-for="(item,index) in projectList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
          <project-select v-model="formInline.projects"></project-select>
        </el-form-item>
        <el-form-item label="客户来源：">
          <user-source v-model="formInline.clueSources"></user-source>
        </el-form-item>
        <el-form-item label="广告代号：">
          <!-- <el-select v-model="formInline.adSource" filterable clearable>
            <el-option v-for="(item,index) in adCodeList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
           <adcode-select v-model="formInline.adSources"></adcode-select>
        </el-form-item>
        <el-form-item label="所属部门：">
          <depart-ment v-model="formInline.departmentId"></depart-ment>
        </el-form-item>
        <el-form-item label="关键词：">
          <el-input v-model="formInline.term" placeholder="请输入客户姓名/电话"></el-input>
        </el-form-item>
      </el-form>
      <div class="search_btn_box">
        <el-button type="primary" size="small" @click="onSearch">筛选</el-button>
        <el-button type="default" size="small" @click="rest">清空筛选</el-button>
      </div>
    </div>
    <!-- 搜索区域 end -->

    <!-- 表格 开始 -->
    <div class="table_box">
      <!-- 操作区域 开始 -->
      <div class="action_box">
        <el-button type="primary" size="small" @click="openCollectDialog('收款变动',4)">收款变动</el-button>
        <!-- <el-button type="primary" size="small" @click="openCollectDialog('错误金额修正',7)">错误金额修正</el-button> -->
        <!-- <el-button type="default" size="small" :loading="eloading" @click="downloadExcel">导出筛选结果</el-button> -->
        <auth-button uid="1040201" type="default" size="small" @click.native="downloadExcel" :loading="eloading">导出筛选结果</auth-button>
      </div>
      <!-- 操作区域 end -->

      <el-table ref="elTable" class="el_table" size="small" :data="tableData" @sort-change="sortChange">
        <el-table-column prop="channelName" label="客户信息" width="150px">
          <template slot-scope="{row}">
            <tab-user :user="userFormatter(row)"></tab-user>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalName" label="预约医院" show-overflow-tooltip width="160" />
        <el-table-column prop="appointmentTime" label="预约时间" sortable="custom" show-overflow-tooltip width="120">
          <template slot-scope="{row}">{{showTime(row.appointmentTime)}}</template>
        </el-table-column>
        <el-table-column prop="dealProject" label="成交项目">
          <template slot-scope="{row}">
            <div class="tag_list">
              <div class="tag" v-for="(item,index) in (row.dealProject?row.dealProject.split(','):[])" :key="index">{{item}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="dealType" label="收款类型">
        </el-table-column>
        <el-table-column prop="dealAmount" label="成交金额" show-overflow-tooltip>
          <template slot-scope="{row}">{{row.dealAmount || 0}}</template>
        </el-table-column>
        <el-table-column prop="collectMoney" label="收款金额" show-overflow-tooltip />
        <el-table-column prop="collectTime" label="收款时间" sortable="custom" show-overflow-tooltip width="120">
          <template slot-scope="{row}">{{showTime(row.collectTime)}}</template>
        </el-table-column>
        <el-table-column prop="principal" label="负责人" show-overflow-tooltip width="80" />
        <el-table-column prop="outpatientFeedback" label="门诊反馈">
          <template slot-scope="{row}">
            <el-tooltip class="item" effect="dark" placement="top-start">
              <div slot="content" style="max-width:240px">{{row.outpatientFeedback}}</div>
              <div class="tab_txt">{{row.outpatientFeedback}}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="" label="操作" width="120" align="center">
          <template slot-scope="{row}">
            <!-- <auth-button uid="1040202" type="primary" size="mini" @click.native="openDialog(row)">修改</auth-button> -->
            <auth-link uid="1040202" type="primary" class="el_link" :underline="false" @click.native="openDialog(row)">修改</auth-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_list">
        <el-pagination background layout="sizes, total,prev, pager, next, jumper" :total="pageTotal" :page-size="pageSize" :page-sizes="pageSizes" :current-page.sync="pageNumber" @current-change="getList" @size-change="changePageSize" />
      </div>
    </div>
    <!-- 表格 end -->

    <!-- 修改收款记录 开始 -->
    <glsx-dialog :show="showDialog" title="修改收款记录" @close="closeDialog()">
      <div class="">
        <el-form ref="editForm" :model="editForm" :rules="editFormRules" class="edit_form" size="small" label-width="120px">
          <el-form-item label="客户姓名：">{{currentInfo.name}}</el-form-item>
          <el-form-item label="客户手机：">{{currentInfo.phone}}</el-form-item>
          <el-form-item label="预约门诊：">{{currentInfo.hospitalName}}</el-form-item>
          <el-form-item label="预约时间：">{{currentInfo.appointmentTime}}</el-form-item>
          <el-form-item label="成交项目：">{{currentInfo.dealProject}}</el-form-item>
          <el-form-item label="收款类型：">{{currentInfo.dealType}}</el-form-item>
          <el-form-item label="成交金额：" class="long_form_item" prop="dealAmount">
            <el-input v-model="editForm.dealAmount" class="a_input"></el-input>
          </el-form-item>
          <el-form-item label="收款金额：" class="long_form_item" prop="collectMoney">
            <el-input v-model="editForm.collectMoney" class="a_input"></el-input>
          </el-form-item>
          <el-form-item label="收款时间：" class="long_form_item" prop="collectTime">
            <el-date-picker v-model="editForm.collectTime" type="datetime" class="a_input" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="修改备注：" class="long_form_item">
            <el-input type="textarea" v-model="editForm.remark" resize="none" rows="3"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" :loading="loading" @click="saveInfo()">保存</el-button>
        <el-button type="default" size="small" @click="closeDialog()">取消</el-button>
      </div>
    </glsx-dialog>
    <!-- 修改收款记录 end -->

  </div>
</template>

<script>
import {
  showToast,
  showModal,
  deepClone,
  broadcast,
  received,
} from "@/common/util";
import { exportExcel } from "@/common/common";
import GlsxDialog from "@/components/Dialog/index";
import moment from "moment";
import TabUser from "@/components/user";
import {
  GETDEALCOLLECTSEARCH,
  DEALCOLLECTEXPORT,
  EDITDEALCOLLECTINFO,
} from "@/http/deal";
import { DEALLISTTYPELIST } from "@/common/constants";
import {
  GETCITYOPTIONS,
  GETUSEROPTIONS,
  GETPROJECTOPTIONS,
  GETADSOURCEOPTIONS,
} from "@/http/system";
import { GETHOSPITALOPTIONS } from "@/http/hospital";
import AuthButton from "@/components/auth-button";
import AuthLink from "@/components/auth-button/link";
import CitySelect from "@/components/select/city";
import ProjectSelect from "@/components/select/project";
import UserSelect from "@/components/select/user";
import AdcodeSelect from "@/components/select/adCode";
import UserSource from '@/components/select/source'
export default {
  components: {
    GlsxDialog,
    TabUser,
    AuthButton,
    AuthLink,
    CitySelect,
    ProjectSelect,
    AdcodeSelect,
    UserSelect,
    UserSource
  },
  data() {
    return {
      formInline: {},
      tableData: [],
      pageTotal: 0,
      pageNumber: 1,
      pageSizes: [10, 20, 50, 100],
      pageSize: 20,
      orderTime: [],
      orderTime2: [],
      showDialog: false,
      loading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "前天",
            onClick(picker) {
              const end = moment().subtract(2, "days").format("YYYY-MM-DD");
              const start = moment().subtract(2, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = moment().subtract(1, "days").format("YYYY-MM-DD");
              const start = moment().subtract(1, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "今天",
            onClick(picker) {
              const end = moment().subtract(0, "days").format("YYYY-MM-DD");
              const start = moment().subtract(0, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "明天",
            onClick(picker) {
              const end = moment().add(1, "days").format("YYYY-MM-DD");
              const start = moment().add(1, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "后天",
            onClick(picker) {
              const end = moment().add(2, "days").format("YYYY-MM-DD");
              const start = moment().add(2, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      eloading: false,
      cityList: [],
      projectList: [],
      userList: [],
      hospitalList: [],
      DEALLISTTYPELIST: DEALLISTTYPELIST,
      adCodeList: [],
      editForm: {},
      currentInfo: {},
      editFormRules: {
        dealAmount: [
          { required: true, message: "请输入成交金额", trigger: "blur" },
        ],
        collectMoney: [
          { required: true, message: "请输入收款金额", trigger: "blur" },
        ],
        collectTime: [
          { required: true, message: "请选择收款时间", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    $route: {
      handler: function (e) {
        this.getList();
      },
      immediate: true,
    },
  },
  created() {
    this.getList();
    this.getHospital();
    this.getProject();
    this.getUser();
    this.getCity();
    this.getAdCodeList();
    received("commom.edit.success", this.getList);
  },
  mounted() {},
  methods: {
    /** 重置 */
    rest() {
      this.formInline = {};
      this.orderTime = [];
      this.orderTime2 = [];
      this.getList();
    },

    /** 每页展示 */
    changePageSize(e) {
      this.pageSize = e;
      this.getList();
    },

    /** 获取参数 */
    getParams() {
      let oParams = JSON.parse(JSON.stringify(this.formInline));
      let n = oParams.orderTime;
      let m = oParams.orderTime2;
      let nm = oParams.applyTime;

      if (n && n.length > 0) {
        oParams.orderStartTime = n[0];
        oParams.orderEndTime = n[1];
      }

      if (m && m.length > 0) {
        oParams.collectStartTime = m[0];
        oParams.collectEndTime = m[1];
      }

      if (nm && nm.length > 0) {
        oParams.enrollStartTime = nm[0];
        oParams.enrollEndTime = nm[1];
      }

      delete oParams.applyTime;
      delete oParams.orderTime;
      delete oParams.orderTime2;

      oParams.pageNumber = this.pageNumber;
      oParams.pageSize = this.pageSize;
      return oParams;
    },

    /** 获取列表 */
    getList() {
      let _this = this;
      let oParams = this.getParams();
      oParams.orderId = this.$route.query.id;
      GETDEALCOLLECTSEARCH(oParams).then((res) => {
        let obj = res.data || {};
        _this.tableData = obj.list || [];
        _this.pageTotal = obj.totalElements;
      });
    },

    // 格式化处理用户信息
    userFormatter(row) {
      let o = deepClone(row);
      o.customerName = o.name;
      o.customerPhone = o.phone;
      o.id = row.clueId;
      return o;
    },

    // 监听组件变化
    onChange(e) {
      if (e.id) {
        this[e.id] = false;
      }
    },

    // 导出excel
    downloadExcel() {
      let _this = this;
      let o = deepClone(_this.formInline);
      let m = Object.keys(o);
      if (m.length > 0) {
        showModal({
          message: "确定是否导出筛选条件下面所有收款记录?",
          showCancelButton: true,
          type: "warning",
          success: function () {
            _this.dowloadExcelFile();
          },
        });
        return false;
      }
      showToast({
        message: "请选择筛选条件后再导出",
      });
    },

    // 下载excel
    dowloadExcelFile() {
      let _this = this;
      let oParams = this.getParams();
      let options = {};
      options.method = "GET";
      options.data = oParams;
      options.url = DEALCOLLECTEXPORT;
      options.fileName = "收款记录.xlsx";
      _this.eloading = true;
      exportExcel(options).then((res) => {
        _this.eloading = false;
      });
    },

    // 获取所有项目
    getProject() {
      GETPROJECTOPTIONS().then((res) => {
        this.projectList = res.data || [];
      });
    },

    // 获取所有医院
    getHospital(code) {
      let oParams = {};
      oParams.cities = code;
      GETHOSPITALOPTIONS(oParams).then((res) => {
        this.hospitalList = res.data || [];
      });
    },

    // 获取负责人列表
    getUser(name) {
      GETUSEROPTIONS({ username: name }).then((res) => {
        this.userList = res.data || [];
      });
    },

    // 获取所有城市
    getCity() {
      GETCITYOPTIONS().then((res) => {
        this.cityList = res.data || [];
      });
    },

    // 打开收款变动
    openCollectDialog(title, status) {
      broadcast("customer.collect.add", { status: status, title: title });
    },
    // 格式化展示时间
    showTime(str) {
      if (!str) {
        return "";
      }
      return moment(str).format("yyyy-MM-DD HH:mm");
    },

    // 获取广告代号
    getAdCodeList(id) {
      GETADSOURCEOPTIONS().then((res) => {
        this.adCodeList = res.data || [];
      });
    },

    // 打开弹框
    openDialog(row) {
      this.showDialog = true;
      this.currentInfo = row;
    },

    // 关闭弹框
    closeDialog() {
      this.showDialog = false;
      this.currentInfo = {};
      this.editForm = {};
      this.$refs.editForm.clearValidate();
    },

    // 保存数据
    saveInfo() {
      let _this = this;
      _this.$refs.editForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        let oParams = deepClone(_this.editForm);
        oParams.id = this.currentInfo.id;
        _this.loading = true;
        EDITDEALCOLLECTINFO(oParams).then((res) => {
          _this.loading = false;
          if (res.code == 200) {
            showToast({
              message: "修改成功",
              type: "success",
            });
            _this.getList();
            _this.closeDialog();
          }
        });
      });
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      this.formInline.orderField = prop;
      if (order == "ascending") {
        this.formInline.orderDirection = "ASC";
      } else {
        this.formInline.orderDirection = "DESC";
      }
      this.getList()
    },

    // 搜索
    onSearch(){
      this.pageNumber = 1;
      this.getList()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/style/customer/index.scss";
.edit_form {
  display: flex;
  flex-wrap: wrap;
  .el-form-item {
    flex: 0 0 50%;
  }
  .long_form_item {
    flex: 0 0 100%;
  }
  .a_input {
    width: 50%;
  }
}
</style>
